﻿using EMall.Domain;
using System.Text.Json;

namespace EMall.ProductService.ProductSkus
{
    public class ProductSku : AggregateRoot<int>
    {
        public int ProductId { get; private set; }
        public string Spec { get; private set; }
        public decimal CostPrice { get; private set; }
        public decimal SalePrice { get; private set; }
        public int AvailableStock { get; private set; }
        protected ProductSku() { }
        public ProductSku(int productId, string spec, decimal costPrice, decimal salePrice, int defaultStock)
        {
            ProductId = productId;
            Spec = spec;
            CostPrice = costPrice;
            SalePrice = salePrice;
            AvailableStock = defaultStock;
            AddDomainEvent(new EntityCreatedDomainEvent<ProductSku>(this));
        }
        public void Update(string spec, decimal costPrice, decimal salePrice)
        {
            var originJson = JsonSerializer.Serialize(this);
            Spec = spec;
            CostPrice = costPrice;
            SalePrice = salePrice;
            AddDomainEvent(new EntityUpdatedDomainEvent<ProductSku>(originJson, this));
        }
        public void RemoveStock(int quantity)
        {
            if (AvailableStock - quantity < 0)
            {
                throw new ApplicationException($"当前库存为{AvailableStock}，不足{quantity}");
            }
            AvailableStock -= quantity;
        }
        public int AddStock(int quantity)
        {
            AvailableStock += quantity;
            return AvailableStock;
        }
    }
}
